<?php


namespace App\Services;


use App\Models\Menu;
use App\Utils\Code;
use App\Utils\Tree;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class MenuService extends BaseService
{
    /**
     * 创建数据
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function store(array $params) {
        if (!$this->checkParams($params)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        $model = new Menu();
        if (isset($params['pid']) && is_numeric($params['pid'])){
            if ($params['pid'] && !$this->show($params['pid'], true, false)){
                throw new \Exception('不存在的上级ID主键', Code::PARAMETER_ERROR);
            }
            $model->pid = (int)$params['pid'];
        }
        if (Menu::where('menu_name', $params['menu_name'])->where('pid', (int)$model->pid)->first()) {
            throw new \Exception('该菜单已经存在', Code::EXIST_REPEAT);
        }
        $model->menu_name = $params['menu_name'];
        $model->module = $params['module'];
        if (key_exists('uri', $params)) {
            $model->uri = $params['uri'];
        }
        if (isset($params['icon']) && $params['icon']) {
            $model->icon = $params['icon'];
        }
        if (isset($params['is_buy']) && is_numeric($params['is_buy'])) {
            $model->is_buy = (int)$params['is_buy'];
        }
        if (isset($params['expands']) && $params['expands']) {
            $model->expands = $params['expands'];
        }
        if ($model->is_buy && (!isset($model->expands['unit_price']) || !$model->expands['unit_price'])) {
            throw new \Exception('售卖价格不能为空', Code::PARAMETER_ERROR);
        }
        if (isset($params['is_hide']) && is_numeric($params['is_hide'])) {
            $model->is_hide = (int)$params['is_hide'];
        }

        if (isset($params['sort']) && is_numeric($params['sort'])){
            $model->sort = (int)$params['sort'];
        }
        if (isset($params['status']) && is_numeric($params['status'])){
            $model->status = (int)$params['status'];
        }
        if (isset($params['rules']) && $params['rules']) {
            $model = \DB::transaction(function () use ($model, $params){
                $model->save();
                // 同步中间关系
                $model->rules()->sync($params['rules']);
                return $model;
            });
        } else {
            $model->save();
        }
        return $this->show($model->menu_id, false);
    }

    /**
     * 数据信息
     * @param $id
     * @param bool $simple
     * @param bool $abnormal
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function show($id, $simple = true, $abnormal = true) {
        $model = Menu::where('menu_id', $id);
        if (!$simple){
            $model = $model->with(['rules' => function(BelongsToMany $belongsToMany){
                $belongsToMany->select(['bind_menu_rule.rule_id', 'rule_name', 'pid', 'uri']);
            }]);
        }
        $model = $model->first();
        if (!$model && $abnormal){
            throw new \Exception('不存在的菜单ID主键', Code::EMPTY_DATA);
        }
        return $model;
    }

    /**
     * 更新数据
     * @param $id
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function update($id, array $params) {
        if (!$this->checkParams($params, true)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        $model = $this->show($id, true, true);
        if (isset($params['menu_name']) && $params['menu_name']) {
            $model->menu_name = $params['menu_name'];
        }
        if (isset($params['module']) && is_numeric($params['module'])) {
            $model->module = $params['module'];
        }
        if (isset($params['pid']) && is_numeric($params['pid'])) {
            $menuList = Menu::where('module', $model->module)->get()->toArray();
            $model->pid = (int)$params['pid'];
            if ($model->pid && in_array($model->pid, Tree::instance()->toChildrenId($model->menu_id, 'menu_id', $menuList))){
                throw new \Exception('上级主键非法', Code::LACK_OF_CONDITIONS);
            } elseif ($model->pid && !$this->show($model->pid, true, false)) {
                throw new \Exception('不存在的上级ID主键', Code::PARAMETER_ERROR);
            }
        }
        if (key_exists('uri', $params)) {
            $model->uri = $params['uri'];
        }
        if (isset($params['icon']) && $params['icon']) {
            $model->icon = $params['icon'];
        }
        if (isset($params['is_buy']) && is_numeric($params['is_buy'])) {
            $model->is_buy = (int)$params['is_buy'];
        }
        if (key_exists('expands', $params)) {
            if ($params['expands']) {
                $model->expands = $params['expands'];
            } else {
                $model->expands = [
                    'unit_price' => null,
                    'price_tactics' => []
                ];
            }
        }
        if ($model->is_buy) {
            if (!isset($model->expands['unit_price']) || !$model->expands['unit_price']) {
                throw new \Exception('售卖价格不能为空', Code::PARAMETER_ERROR);
            }
        }
        if (isset($params['is_hide']) && is_numeric($params['is_hide'])) {
            $model->is_hide = (int)$params['is_hide'];
        }
        if (isset($params['sort']) && is_numeric($params['sort'])) {
            $model->sort = $params['sort'];
        }
        if (isset($params['status']) && is_numeric($params['status'])) {
            $model->status = $params['status'];
        }
        if (isset($params['rules'])) {
            if (is_array($params['rules']) && $params['rules']) {
                $model = \DB::transaction(function () use ($model, $params){
                    // 同步中间关系
                    $model->rules()->sync($params['rules']);
                    $model->save();
                    return $model;
                });
            } else {
                \DB::table('bind_menu_rule')->where('menu_id', (int)$id)->delete();
            }
        }
        $model->save();
        return $this->show($model->menu_id, false);
    }

    /**
     * 删除数据
     * @param $id
     * @return mixed
     * @throws \Throwable
     */
    public function destroy($id) {
        if (!$this::$admin) {
            throw new \Exception('你没有权限删除节点', Code::LACK_OF_CONDITIONS);
        }
        if (Menu::where('pid', (int)$id)->exists()) {
            throw new \Exception('该层级下包含有子级元素', Code::LACK_OF_CONDITIONS);
        }
        $model = $this->show($id, true, true);
        return \DB::transaction(function () use ($model) {
            \DB::table('bind_menu_rule')->where('rule_id', $model->rule_id)->delete();
            return $model->delete();
        });
    }

    /**
     * 数据列表
     * @param array $params
     * @return array
     */
    public function lists(array $params = []) {
        $lists = Menu::where('module', isset($params['module']) ? (int)$params['module'] : 1)
            ->orderBy('sort', 'asc')->get()->toArray();
        if (isset($params['format']) && $params['format'] == 'list'){
            $lists = Tree::instance()->treeFormat($lists, 'children', null);
        } else {
            $lists = Tree::instance()->toTree($lists, 'menu_id');
        }
        return $lists;
    }

    /**
     * 验证参数
     * @param array $params
     * @param bool $isUpdate
     * @return array
     * @throws \Exception
     */
    private function checkParams(array $params, $isUpdate = false){
        $rules = [
            'menu_name' => ['bail', 'required', 'string', 'between:2,6'],
            'module' => ['bail', 'required', 'integer', 'in:0,1'],
            'unit_price' => ['bail', 'nullable', 'numeric', 'nullable', 'gt:0'],
            'pid' => ['bail', 'nullable', 'integer'],
            'uri' => ['bail', 'nullable', 'string'],
            'sort' => ['bail', 'nullable', 'integer'],
            'status' => ['bail', 'nullable', 'integer', 'in:0,1']
        ];
        if ($isUpdate){
            // 删除必选条件
            foreach ($rules as $field => &$rule){
                if (isset($rule[1]) && $rule[1] == 'required') {
                    $rule[1] = 'nullable';
                }
            }
        }
        $validator = \Validator::make($params, $rules, [], [
            'menu_name' => '菜单标题',
            'module' => '归属模块',
            'unit_price' => '销售单价',
            'pid' => '上级主键',
            'uri' => '请求路径',
            'sort' => '排序数值',
            'status' => '可用状态'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        return $params;
    }
}
